<?php

namespace frontend\modules\marketing\controllers;

use backend\modules\orders\models\ShareRebUser;
use common\models\Wxuser;
use frontend\modules\base\controllers\BaseController;
use frontend\modules\orders\models\OrderGoods;
use frontend\modules\orders\models\OrderInfo;
use Yii;
use frontend\modules\marketing\models\ShareReb;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * 用户返利表
 *
 * Class SharerebController
 * @package frontend\modules\marketing\controllers
 */
class SharerebController extends BaseController
{
    public $enableCsrfValidation = false;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 获取活动货物订单
     * @desc 我的活动MyActive（）
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionMyactive()
    {
        $model = new OrderInfo();
        $goodsActive = $model->MyActive();
        $message = ['code' => 200, 'message' => '获取活动数据成功', 'data' => ['goodsActive'=>$goodsActive]];
        return json_encode($message);
    }

    /**
     * 微信验证数据
     * @desc 微信验证数据接口
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionApiconfall()
    {
        $post = Yii::$app->request->post();
        if($post){
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $signPackage = $wechat->jsApiConfigConfall();
            $message = ['code' => 200, 'message' => '验证数据', 'signPackage' =>$signPackage];
            return json_encode($message);
        }
    }

    /**
     * 微信验证数据
     * @desc 微信验证数据接口
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionJswxconfall()
    {
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
        $wechat = Yii::$app->wechat;
        $signPackage = $wechat->jsApiConfig();
//        $message = ['code' => 200, 'message' => '验证数据', 'signPackage' =>$signPackage];
        return $this->renderPartial('confall',['signPackage'=>$signPackage]);
    }

    /**
     *
     */
    public function actionJswxconf()
    {
        $ordersn = $_GET['ordersn'];
        $ispayed = $_GET['ispayed'];
        $qcode = 0;
        if($ispayed) {
            $order = OrderInfo::findOne(['order_sn'=>$ordersn]);
            if($order) {
                $qcode = Wxuser::findOne($order->user_id)->qcode;
            }
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $signPackage = $wechat->jsApiConfig();
            $this->userSave(Wxuser::findOne($order->user_id)->openid);

            return $this->renderPartial('index',['signPackage'=>$signPackage,'qcode'=>$qcode,'ordersn'=>$ordersn,'order'=>$order]);
        } else {
            $order = OrderInfo::findOne(['order_sn'=>$ordersn]);
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $signPackage = $wechat->jsApiConfig();

            return $this->renderPartial('pay_fail',['signPackage'=>$signPackage,'qcode'=>$qcode,'ordersn'=>$ordersn,'goods_amount'=>$order->goods_amount,'order'=>$order]);
        }
    }

    public function actionActivity()
    {
//        return $this->redirect('https://www.pooai.com/mobile/appDown.html');
        $qcode = $_GET['qcode'];
        $ordersn = $_GET['ordersn'];
        if($qcode&&$ordersn){
            return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/activity.html?qcode=$qcode&ordersn=$ordersn");
        }
    }

    /**
     * @return \yii\web\Response
     */
    public function actionGodetail()
    {
        $qcode = isset($_GET['qcode'])?$_GET['qcode']:'';
        $ordersn = isset($_GET['ordersn'])?$_GET['ordersn']:'';
        if($qcode&&$ordersn){

        }else{
            $post = Yii::$app->request->post();
            $postData = $post['data'];
            $qcode = $postData['qcode'];
            $ordersn = $postData['ordersn'];
        }
//        print_r('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dee5a1c01f37b68&redirect_uri='.Yii::$app->params['domurl'].'wx%2Ffrontend%2Fweb%2Findex.php%3Fr%3Dsite%252Fsite%252Fdetail%26qcode%3D'.$qcode.'%26ordersn%3D'.$ordersn.'&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect');exit;
        return $this->redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dee5a1c01f37b68&redirect_uri='.Yii::$app->params['domurl'].'wx%2Ffrontend%2Fweb%2Findex.php%3Fr%3Dsite%252Fsite%252Fdetail%26qcode%3D'.$qcode.'%26ordersn%3D'.$ordersn.'&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect');
    }

    /**
     * @return \yii\web\Response
     */
    public function actionGoindex()
    {
        return $this->redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dee5a1c01f37b68&redirect_uri=https%3A%2F%2Fwww.pooai.cn%2Fwx%2Ffrontend%2Fweb%2Findex.php%3Fr%3Dsite%252Fsite%252Findex&time=1100&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect');
    }

    /**
     * 用户可用返利处理
     *
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionSetreb()
    {
        $ordersn = $_POST['ordersn'];

        if($ordersn) {
            $beginTransaction = Yii::$app->db->beginTransaction();
            try{
                $orderInfo = OrderInfo::findOne(['order_sn'=>$ordersn]);
                if($orderInfo->is_share==0){
                    $userid = Yii::$app->UserInfo->userid;
                    //获得订单is_gift商品量
                    $orderGoods = OrderGoods::findAll(['order_id'=>$orderInfo->order_id,'is_gift'=>1]);
                    $goodsNumAll = 0;
                    foreach($orderGoods as $k=>$v) {
                        $goodsNumAll += $v->goods_number;
                    }

                    if($goodsNumAll>0) {
                        //是否已经参与过，再次参与
                        $shareRebUser = ShareRebUser::findOne(['user_id'=>$userid]);
                        if($shareRebUser) {
                            $shareRebUser->reb_number += $goodsNumAll*10;
                            if(!$shareRebUser->save()){
                                throw new Exception(json_encode($shareRebUser->errors));
                            }
                        } else {
                            $shareRebUser = new ShareRebUser();
                            $shareRebUser->user_id = $userid;
                            $shareRebUser->reb_number = $goodsNumAll*10;
                            if(!$shareRebUser->save()){
                                throw new Exception(json_encode($shareRebUser->errors));
                            }
                        }

                        $orderInfo->is_share = 1;
                        if(!$orderInfo->save()) {
                            throw new Exception(json_encode($orderInfo->errors));
                        }
                    }
                }
                $beginTransaction->commit();
                $message = ['code' => 200, 'message' => '成功参与', 'data' => []];
                return json_encode($message);
            }catch (Exception $e){
                $beginTransaction->rollBack();
                $message = ['code' => 500, 'message' => $e->getMessage(), 'data' => $ordersn];
                return json_encode($message);
            }
        }
    }

    /**
     * 设置用户获取福利日照
     * @return bool
     * @throws \yii\db\Exception
     */
    public function actionSetreblog()
    {
        $ordersn = isset($_POST['ordersn'])?$_POST['ordersn']:'';
        if($_POST['checkcode']!=="@pooai@"){
            return false;
        }
        if(!$ordersn) {
            return false;
        }

        $orderARR = OrderGoods::find()
            ->select('og.*')
            ->from('order_goods AS og')
            ->leftJoin('order_info AS oi','oi.order_id = og.order_id')
            ->where(['order_sn'=>$ordersn,'og.is_gift'=>1])
            ->asArray()
            ->All();

        if(!$this->addshare($ordersn)){
            return false;
        }
        foreach($orderARR as $k=>$v) {
            $refere_id = $v['refere_id'];
            if($refere_id) {
                $Wxuser = Wxuser::findOne(['qcode'=>$refere_id]);
                $shareRebUser = ShareRebUser::findOne(['user_id'=>$Wxuser->id]);
                if($shareRebUser->reb_number<=$shareRebUser->reb_used_number) {

                } else {
                    $shareRebUser->reb_used_number = $shareRebUser->reb_used_number +$v['goods_number'];
                    if(ShareReb::findOne(['buyer_id'=>$v['user_id'],'order_id'=>$v['order_id'],'goods_id'=>$v['goods_id'],'user_id'=>$Wxuser->id])) {
                        continue;
                    }
                    $shareReb = new ShareReb();
                    $shareReb->user_id = $Wxuser->id;
                    $shareReb->buyer_id = $v['user_id'];
                    $shareReb->order_id = $v['order_id'];
                    $shareReb->goods_id = $v['goods_id'];
                    $shareReb->goods_number = $v['goods_number'];
                    $shareReb->reb_money = round($v['goods_number']*$v['shop_price']/10,2);
                    $shareRebUser->save();
                    $shareReb->save();
                }
            }
        }
        return true;
    }

    public function addshare($ordersn){
        $orderInfo = OrderInfo::findOne(['order_sn'=>$ordersn]);
        if($orderInfo->is_share==0){
            $userid = $orderInfo->user_id;
            //获得订单is_gift商品量
            $orderGoods = OrderGoods::findAll(['order_id'=>$orderInfo->order_id,'is_gift'=>1]);
            $goodsNumAll = 0;
            foreach($orderGoods as $k=>$v) {
                $goodsNumAll += $v->goods_number;
            }

            if($goodsNumAll>0) {
                //是否已经参与过，再次参与
                $shareRebUser = ShareRebUser::findOne(['user_id'=>$userid]);
                if($shareRebUser) {
                    $shareRebUser->reb_number += $goodsNumAll*10;
                    if(!$shareRebUser->save()){
                        return false;
                    }
                } else {
                    $shareRebUser = new ShareRebUser();
                    $shareRebUser->user_id = $userid;
                    $shareRebUser->reb_number = $goodsNumAll*10;
                    if(!$shareRebUser->save()){
                        return false;
                    }
                }

                $orderInfo->is_share = 1;
                if(!$orderInfo->save()) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取用户返利情况
     * @desc 我的活动返利情况
     *
     * @param string $access_token |令牌access_token|yes|32位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionGreb()
    {
        $user_id = Yii::$app->UserInfo->userid;
        $shareRebARR = ShareReb::find()
            ->select('sr.* ,g.goods_image,g.goods_name,uid.wx_name,uid.wx_images,u.wx_name as buyer_name,u.wx_images as buyer_images,oi.order_sn ')
            ->from('share_reb AS sr')
            ->leftJoin('goods AS g','sr.goods_id = g.goods_id')
            ->leftJoin('user AS u','sr.buyer_id = u.id')
            ->leftJoin('user AS uid','uid.id = sr.user_id')
            ->leftJoin('order_info AS oi','sr.order_id = oi.order_id')
            ->where(['sr.user_id'=>$user_id])
            ->asArray()->all();

        $shareRebUser = ShareRebUser::findOne(['user_id'=>$user_id]);
        if($shareRebUser){
            $reb_number = $shareRebUser->reb_number;
            $reb_used_number = $shareRebUser->reb_used_number;
            $allRebMoney = ShareReb::find()->where(['user_id'=>$user_id])->sum('reb_money');
            $tolInfo = ['reb_number'=>$reb_number,'reb_used_number'=>$reb_used_number,'allRebMoney'=>$allRebMoney];
            $message = ['code' => 200, 'message' => '成功参与', 'data' => $shareRebARR,'tolInfo'=>$tolInfo];
            return json_encode($message);
        }else {
            $message = ['code' => 500, 'message' => '未参与', 'data' => []];
            return json_encode($message);
        }

    }

//    public function actionGetorder()
//    {
//        $orderIDS = OrderInfo::find()->where(['pay_status'=>2,'is_share'=>1])->select(['order_id'])->asArray()->all();
//        if($orderIDS) {
//            foreach($orderIDS as $k=>$v) {
//                OrderGoods::find()->where(['is_gift'=>1,$])
//            }
//        }
//    }

    /**
     * 二维码分享页面
     */
    public function actionJswxerw()
    {
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
        $wechat = Yii::$app->wechat;
        $signPackage = $wechat->jsApiConfig();
        $userid = Yii::$app->UserInfo->userid;
        $ordersn = $this->GetOrderId($userid);
        return $this->renderPartial('erwpage',['ordersn'=>$ordersn,'signPackage'=>$signPackage]);
    }

    public function GetOrderId($id)
    {
        $ordersn = '';
        $orderInfoArrs = OrderInfo::find()->where(['user_id'=>$id,'pay_status'=>2])->all();
        foreach($orderInfoArrs as $k=>$model) {
            $num = OrderGoods::find()->where(['order_id'=>$model->order_id])->sum("goods_number");
            $useNum = OrderGoods::find()->where(['re_ordersn'=>$model->order_sn])->sum("goods_number");
            if($num*10>$useNum) {
                $ordersn = $model->order_sn;
                break;
            }
            $ordersn = $model->order_sn;
        }
        return $ordersn;
//        return OrderInfo::find()->where(['user_id'=>$id,'pay_status'=>2])->one()->order_sn;
    }

    /**
     * 二维码分享页面
     */
    public function actionTest()
    {
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
        $wechat = Yii::$app->wechat;
        $signPackage = $wechat->jsApiConfig();
        $userid = Yii::$app->UserInfo->userid;
        $ordersn = $this->GetOrderId($userid);
        $user = Wxuser::findOne($userid);
        return $this->renderPartial('erwindex',['qcode'=>$user->qcode,'ordersn'=>$ordersn,'signPackage'=>$signPackage,'tx_images'=>$user->tx_images,'ewm_images'=>$user->ewm_images,'wx_name'=>$user->wx_name]);
    }

    public $randPath = '';
    /**
     * 二维码上传，头像下载
     */
    public function actionUploadw()
    {
        $this->randPath = time().'-'.rand(10,1000);
        $post = $_POST;
        $imgStr =isset($post['data'])?$post['data']:'';
        $imgStr = str_replace(" ","+",$imgStr);
        $userid = Yii::$app->UserInfo->userid;
        $user = Wxuser::findOne($userid);
        $ewmPath = $this->createImg('Ewm',$imgStr);
        $txPath = $this->downImg('Tx',$user->wx_images);
        $user->tx_images = $txPath;
        $user->ewm_images = $ewmPath;
        $user->save();
        return json_encode(['code'=>200,'ewmPath'=>$ewmPath,'txPath'=>$txPath]);
    }

    /**
     * 二维码上传，头像下载
     */
    public function actionSaveimg()
    {
        $post = $_POST;
        $imgStr =isset($post['data'])?$post['data']:'';
        $imgStr = str_replace(" ","+",$imgStr);

        $savePath = $this->createImg('Save',$imgStr);
        $user = Wxuser::findOne(Yii::$app->UserInfo->userid);
        $user->qcode_images = $savePath;
        if($user->save()) {
            return json_encode(['code'=>200,'savePath'=>$savePath]);
        }
    }

    /***
     * @param $name
     * @param $imgStr
     * @return string
     */
    public function createImg($name,$imgStr)
    {
        $baseUrl = Yii::$app->basePath;
        $webUrlBaseOnApp= '/web/upload/canvas/'.Yii::$app->UserInfo->userid.'/';
        $baseImages = $baseUrl.$webUrlBaseOnApp;
        is_dir($baseImages) OR mkdir($baseImages, 0777, true);

        $imageName = $name.$this->randPath.'.png';
        $finalPath = $baseImages.$imageName;

        if (!preg_match('/data:([^;]*);base64,(.*)/', $imgStr, $matches)) {
            die("error");
        }

        $content = base64_decode($matches[2]);
        file_put_contents($finalPath,$content);
        return $webUrlBaseOnApp.$imageName;
    }

    /**
     * @param $name
     * @param $imgPath
     * @return string
     */
    public function downImg($name,$imgPath)
    {
        $baseUrl = Yii::$app->basePath;
        $webUrlBaseOnApp= '/web/upload/canvas/'.Yii::$app->UserInfo->userid.'/';
        $baseImages = $baseUrl.$webUrlBaseOnApp;
        is_dir($baseImages) OR mkdir($baseImages, 0777, true);

        $imageName = $name.$this->randPath.'.png';
        $finalPath = $baseImages.$imageName;

        $ch=curl_init();
        $timeout=5;
        curl_setopt($ch,CURLOPT_URL,$imgPath);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $img=curl_exec($ch);
        curl_close($ch);

        $fp2=@fopen($finalPath,'a');
        fwrite($fp2,$img);
        fclose($fp2);
        return $webUrlBaseOnApp.$imageName;
    }

    /**
     * @return string
     */
    public function actionGettxerw()
    {
        $userid = Yii::$app->UserInfo->userid;
        $user = Wxuser::findOne($userid);
        if($user) {
            $message = ['code' => 200, 'message' => '获取活动数据成功', 'data' => ['tx_images'=>$user->tx_images,'ewm_images'=>$user->ewm_images]];
            return json_encode($message);
        }
    }

    /**
     * 判断用户是否参加了返利活动
     * @desc 判断用户是否参加了返利活动
     *
     * @return string isJoin 是否已经参加 0 未参加 1 已参加
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionIsjoin()
    {
        $userid =  Yii::$app->UserInfo->userid;
        $sru = ShareRebUser::findOne(['user_id'=>$userid]);
        if($sru){
            if($sru->reb_number>$sru->reb_used_number){
                $message = ['code' => 200, 'message' => '已参加', 'isJoin' => 1];
                return json_encode($message);
            }
        }
        $message = ['code' => 200, 'message' => '未参加', 'isJoin' => 0];
        return json_encode($message);
    }

    /**
     * 获取所有用户返利信息(头像，昵称，总额），排序
     * @desc 获取所有用户返利信息(头像，昵称，总额），排序
     *
     * @return string data 用户返利信息数据（头像，昵称，总额）
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionSortusershareb()
    {
        $re = ShareReb::findBySql("
                                  select u.wx_name,u.wx_images,sr.user_id,sum(sr.reb_money) as rebMoney
                                  from share_reb as sr
                                  LEFT JOIN user as u on u.id=sr.user_id
                                  GROUP BY sr.user_id ORDER BY rebMoney DESC "
        )->limit(8)->asArray()->all();
        $message = ['code' => 200, 'message' => '获取成功', 'data' => $re];
        return json_encode($message);
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionP7index()
    {
        return $this->redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dee5a1c01f37b68&redirect_uri=https://www.pooai.cn/wx/frontend/web/index.php%3Fr=site%252Fsite%252Fhgp7detail%26%3Fgoods_id%3Dfb693e10-bcbd-11e8-9a12-d9815894ab60&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect");
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionP8index()
    {
        return $this->redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dee5a1c01f37b68&redirect_uri=https://www.pooai.cn/wx/frontend/web/index.php%3Fr=site%252Fsite%252Fhgdetail%26%3Fgoods_id%3D14737e60-bcbd-11e8-bfe2-31f12f61d8f1&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect");
    }
}
